package org.az.netty_study.p01_nio组件之buffer;

import org.az.netty_study.ByteBufferUtil;

import java.nio.ByteBuffer;
import java.nio.charset.StandardCharsets;

public class _6_字符串和ByteBuffer的转换 {
    public static void main(String[] args) {
        /**
         * 字符串转为ByteBuffer
         *  1.ByteBuffer.allocate(字符串.getBytes())
         *  2.利用Charsets的encode方法:StandardCharsets.UTF_8.encode(字符串)
         *  3.wrap
         */
        //将字符串转为byte[]赋值给ByteBuffer，这种会切换到写模式(position = 0)
        byte[] bytes = "hello".getBytes();
        ByteBuffer buffer1 = ByteBuffer.allocate(16);
        buffer1.put(bytes);
        ByteBufferUtil.debugAll(buffer1);

        //利用nio提供的Charsets类将字符串转为ByteBuffer，这种会切换到读模式(position = 0)
        ByteBuffer buffer2 = StandardCharsets.UTF_8.encode("hello");
        ByteBufferUtil.debugAll(buffer2);

        //nio工具类，这种会切换到读模式
        ByteBuffer buffer3 = ByteBuffer.wrap(bytes);
        ByteBufferUtil.debugAll(buffer3);

        /**
         * ByteBuffer转为字符串
         */
        //ByteBuffer处于读模式才行(position = 0)，因为会从position指向的索引开始转换
        String str2 = StandardCharsets.UTF_8.decode(buffer2).toString();
        System.out.println(str2);
    }
}
